package day27;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client3 {
    public static void main(String[] args) throws IOException {
        //1.创建客户端对象
        Socket client = new Socket("192.168.9.158",9999);
        //反正读取和写入相互独立
        Client3Thread t = new Client3Thread(client);
        t.start();
        //手动输入
        OutputStream os = client.getOutputStream();
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你的姓名:");
        String name = sc.nextLine();
        while(true){
            System.out.println("请输入聊天的内容：输入1结束聊天室,进行私聊输入私聊");
            String line = sc.nextLine();
            if("退出".equals(line)){
                os.write((name+"退出聊天室\n").getBytes());
                break;
            }else if("私聊".equals(line)){
                System.out.println("请输入想私聊的对象");
                String name1 = sc.nextLine();
                os.write((name+"请求私聊:"+name1).getBytes());
            }
            else {
                os.write((name+"说:"+line+"\n").getBytes());
            }
        }
        System.out.println("成功退出");
        t.b = true;
    }
}

class Client3Thread extends Thread{
    Socket client;
    volatile boolean b = false;
    public Client3Thread(Socket client){
        this.client = client;
    }
    public void run(){
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
            while(true) {
                System.out.println(br.readLine());
                if(b) return;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}